package com.Dao.Imp;
import com.Dao.GetUserDao;
import com.Utils.C3P0Utils;
import com.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GetUserDaoImp implements GetUserDao {
    @Override
    public int getUser(String username, String password) throws SQLException {
        int flag = -1;
        String sql = "select  *from userlist where username=?";
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        User user = queryRunner.query(sql, new BeanHandler<>(User.class), username);
        System.out.println(user.getStatus());
        if (user != null) {//如果账户存在
            sql += " and password=?";
            List<User> user1 = queryRunner.query(sql, new BeanListHandler<>(User.class), username, password);
            if (!user1.isEmpty()&&user.getStatus()==1) {//账户密码都正确
                flag = 1;
            }
            if(!user1.isEmpty()&&user.getStatus()==0){//账户密码正确，但是被封禁
                flag=4;
            }
            if(user1.isEmpty()&&user.getStatus()==1){//账户存在，但是用户输入密码错误
                flag = 2;
            }
        } else {//账户不存在或
            flag = 3;
        }
        return flag;
    }
    @Override
    public int getUser(String phone) throws SQLException {
        String sql = "select  *from userlist where username=?";
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        User user = queryRunner.query(sql, new BeanHandler<>(User.class), phone);
        //校验手机号账户是否存在
        if (user != null) {
            return 1;
        } else
            return 2;
    }
    public Map<String,Object> getAllUser(int page, int rows) throws SQLException {
        Map<String,Object> map=new HashMap<>();
        if(page==0){
            page=1;
        }
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        //获取总数
        String sqlCount=" select count(1) from userlist ";
        Long totalCount = queryRunner.query(sqlCount, new ScalarHandler<Long>());
        int start = (page - 1) * rows; // 起始行索引
        String query = "SELECT * FROM userlist LIMIT " + start + ", " + rows;
        List<User> list=queryRunner.query(query,new BeanListHandler<>(User.class));
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalCount / rows);
        map.put("list",list);
        map.put("totalPages",totalPages);
        return map;
    }
}
